<template>
  <el-dialog title="修改账号信息" :visible.sync="dialogvisible" :before-close="handleClose">
    <el-form
      :model="user"
      :rules="rules"
      class="form"
      label-position="right"
      label-width="80px"
      ref="form"
    >
      <el-form-item label="名字" prop="cname">
        <el-input v-model="user.cname" />
      </el-form-item>
      <el-form-item label="头像" prop="photoUrl">
        <singleImgUpload :url.sync="user.photoUrl" dir="sysUser"></singleImgUpload>
      </el-form-item>
      <el-form-item>
        <el-button @click="submit" plain type="primary">修改</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import singleImgUpload from "@/components/upload/SingleImgUpload.vue";

export default {
  components: { singleImgUpload },
  props: {
    // user: {
    //   type: Object,
    //   default: () => {
    //     return {
    //       cname: "",
    //       photoUrl: ""
    //     };
    //   }
    // },
    visible: false
  },
  watch: {
    visible: function() {
      let that = this;
      that.dialogvisible = this.visible;
    }
  },
  data() {
    return {
      rules: {
        name: {
          required: true,
          message: "名字不能为空",
          trigger: "blur"
        }
      },
      dialogvisible: false,
      user: {
        cname: "",
        photoUrl: ""
      }
    };
  },
  computed: {},
  mounted() {
    this.initData();
  },
  methods: {
    initData() {
      this.$https.get("/getUserInfo", {}).then(res => {
        if (res.data.data) {
          this.user = res.data.data;
        }
      });
    },
    submit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const temp = { ...this.user };
          this.$https.postXform("/updateUserInfo", temp).then(res => {
            if (res.data.data) {
              this.$message({
                message: "修改成功",
                type: "success"
              });
            }
            sessionStorage.setItem("name", this.user.cname);
            sessionStorage.setItem("avatar", this.user.photoUrl);
            this.$emit("update:visible", false);
          });
        } else {
          return false;
        }
      });
    },
    handleClose(done) {
      this.$emit("update:visible", false);
      done();
    },
  }
};
</script>

